<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantCode"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in plants"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划到货日期">
          <el-date-picker
            v-model="searchParam.arriveDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getarriveDate"
          />
        </el-form-item>
        <el-form-item label="物料号">
          <el-input
            v-model="searchParam.materialNumber"
            placeholder="请输入物料号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="列表显示的包装ID">
          <el-input
            v-model="searchParam.topUnitId"
            placeholder="请输入列表显示的包装ID"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="openDialogbatches()"
          >打印箱标签</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="openDialogbatchs()"
          >批量填写生产批次</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column
          label="工厂号"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />

        <el-table-column
          label="到货日期"
          prop="arriveDate"
          min-width="130"
          show-overflow-tooltip
          header-align="center"
          align="center"
          :formatter="formatDate"
        />
        <el-table-column
          label="物料号"
          prop="materialNumber"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="要货地点"
          prop="storageLocationName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <!-- <el-table-column
          label="父发货包装ID"
          prop="parentUnitId"
          min-width="100"
          show-overflow-tooltip
        /> -->

        <el-table-column
          label="物料数量"
          prop="materialQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="数量单位"
          prop="unitCode"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="生产批次"
          prop="supplyBatch"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="箱标签号"
          prop="unitBarcode"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />

        <!-- <el-table-column
          label="供应商物料类型"
          prop="supplyMaterialType"
          min-width="100"
        >
          <template #default="scope">
            {{
              useDictionary("SupplyMaterialType", scope.row.supplyMaterialType)
            }}
          </template>
        </el-table-column> -->

        <!-- <el-table-column
          label="包装阶层"
          prop="unitLevel"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="130"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="240"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogbatch(scope.row)"
              ><i-ep-edit />填写生产批次</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <srmorderunit-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <srmorderunit-editbatch
      :visible="addDialogbatch.visible"
      :title="addDialogbatch.title"
      :data="addDialogbatch.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogbatch.readvisible"
      @change-visible="changeVisiblebatch"
    />
    <srmorderunit-editbatchs
      :visible="addDialogbatchs.visible"
      :title="addDialogbatchs.title"
      :data="addDialogbatchs.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      @change-visible="changeVisiblebatchs"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getLodop } from "@/utils/LodopFuncs";

defineOptions({
  name: "SRMSRMORDERUNIT",
  inheritAttrs: false,
});
let plants = ref([]);
let materials = ref([]);
// 请求参数
const requestApi = "/srm/core/srmorderunit/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantCode: "",
  topUnitId: "",
  materialNumber: "",
  arriveDateSearch: [],
  arriveDateStart: "",
  arriveDateEnd: "",
};

const deleteParam = {
  api: "/srm/core/srmorderunit/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const addDialogbatch = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const addDialogbatchs = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});
const addDialogbatches = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
  items: [], // 添加一个名为 items 的数组属性，并初始化为空数组
});
async function getPlants() {
  const data = await request({
    url: "/srm/core/common/getPlantList",
    method: "get",
  });
  plants.value = data.data;
}
async function getMaterials() {
  const data = await request({
    url: `/wms/material/getListForRoughcast`,
    method: "post",
    data: {
      materialType: 1,
    },
  });
  materials.value = data.data;
}
// 查询详情
async function getInfo(id: string) {
  request({
    url: `/srm/core/srmorderunit/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
// 查询详情
async function getInfobatch(id: string) {
  request({
    url: `/srm/core/srmorderunit/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialogbatch.data = data.data;
      addDialogbatch.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
// 查询详情
async function getInfobatches(ids) {
  request({
    url: "/srm/core/srmorderunit/gets",
    method: "post",
    data: ids, // 直接发送ID数组
  })
    .then((data) => {
      addDialogbatches.data = data.data;
      addDialogbatches.visible = true;

      // 遍历返回的数据并赋值给 addDialogbatches
      addDialogbatches.data.forEach((item) => {
        addDialogbatches.items.push(item);
      });
    })
    .catch((res) => {
      console.log(res);
    });
  console.log(addDialogbatches);
}
/** 打开供应商发货包装信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "编辑包装信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增供应商发货包装信息";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开包装单位表单弹窗 */
function openDialogbatch(roleObj?: Object) {
  if (roleObj) {
    addDialogbatch.title = "填写生产批次";
    getInfobatch(roleObj.id);
  }
  addDialogbatch.readvisible = false;
  addDialogbatch.visible = true;
}
/** 打开包装单位表单弹窗 */
function openDialogbatchs() {
  console.log(ids.value);
  addDialogbatchs.data = {
    ids: [...ids.value],
  };
  addDialogbatchs.title = "填写生产批次";
  addDialogbatchs.visible = true;
}
function openDialogbatches() {
  getInfobatches(ids.value);
  setTimeout(function () {
    console.log(addDialogbatches);
    console.log(addDialogbatches.data);
    printFun(addDialogbatches.data);
  }, 1000); // 在这里设置延时时间，单位为毫秒，1000毫秒等于1秒
}
/** 打开供应商发货包装信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "供应商发货包装信息详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function changeVisiblebatch(value: boolean) {
  addDialogbatch.visible = value;
  if (!value) {
    addDialogbatch.data = {};
  }
}
function changeVisiblebatchs(value: boolean) {
  addDialogbatchs.visible = value;
  if (!value) {
    addDialogbatchs.data = {};
  }
}

function getarriveDate(data: any) {
  if (data) {
    searchParam.value.arriveDateStart = data[0];
    searchParam.value.arriveDateEnd = data[1];
  } else {
    searchParam.value.arriveDateStart = "";
    searchParam.value.arriveDateEnd = "";
  }
}
function formatDate(row, column, cellValue) {
  // 假设到货日期的格式为 'YYYY-MM-DD HH:mm:ss'
  // 截取年月日部分
  let datePart = cellValue.split(" ")[0]; // 获取日期部分，例如 'YYYY-MM-DD'
  return datePart;
}

function printFun(pitem) {
  let LODOP = getLodop(); // 获取 LODOP 对象
  LODOP.PRINT_INIT("打印任务标题"); // 初始化打印

  for (let i = 0; i < pitem.length; i++) {
    let currentItem = pitem[i];
    console.log("打印条码", currentItem);

    // 设置打印内容
    LODOP.SET_PRINT_STYLE("FontSize", 7.5);
    LODOP.ADD_PRINT_RECT("0%", "0%", "100%", "100%", 0, 1);
    let y = 50;
    let yy = y;
    LODOP.ADD_PRINT_TEXT(
      y,
      120,
      300,
      15,
      "物料名称：" + currentItem.materialName
    );
    y = yy + 30;
    LODOP.ADD_PRINT_TEXT(
      y,
      120,
      140,
      15,
      "物料号：" + currentItem.materialNumber
    );
    LODOP.ADD_PRINT_TEXT(y, 270, 140, 15, "箱号：" + currentItem.unitCode);
    LODOP.ADD_PRINT_BARCODE(y - 15, 370, 200, 100, "QRCode", currentItem.id);
    y += 20;
    LODOP.ADD_PRINT_TEXT(y, 120, 140, 15, "批次：" + currentItem.supplyBatch);
    LODOP.ADD_PRINT_TEXT(
      y,
      270,
      150,
      15,
      "数量：" + currentItem.materialQuantity
    );
    y += 30;
    let datePart = currentItem.lastUpdateTime.split(" ")[0]; // 获取日期部分，例如 'YYYY-MM-DD'
    LODOP.ADD_PRINT_TEXT(y, 120, 140, 15, "日期：" + datePart);
    LODOP.ADD_PRINT_TEXT(y, 270, 150, 15, "供应商：" + currentItem.partnerCode);
    y += 30;
    LODOP.ADD_PRINT_TEXT(y, 120, 140, 15, "入库类型：毛坯入库");
    y += 30;
    LODOP.ADD_PRINT_TEXT(y, 270, 150, 15, "大连施奈莱克现代物流有限公司");
    if (y < 110) {
      y += 50;
    } else {
      y += 30;
    }
    LODOP.ADD_PRINT_BARCODE(y, 170, 200, 60, "128Auto", currentItem.id);

    LODOP.NEWPAGE();
  }

  LODOP.PREVIEW(); // 预览打印任务
}
</script>
